/*
 * 文件名：MailUtil.java
 * 版权：Copyright 2007-2016 517na Tech. Co. Ltd. All Rights Reserved. 
 * 描述： MailUtil.java
 * 修改人：yanshu
 * 修改时间：2016年1月3日
 * 修改内容：新增
 */
package com.feichuang.chineseWoodCarving.interceptor;

import java.util.Date;
import java.util.Properties;

import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

/**
 * TODO 邮件发送测试类.
 * <p>
 * TODO 详细描述
 * <p>
 * TODO 示例代码
 * 
 * <pre>
 * </pre>
 * 
 * @author hongjian
 */
public class MailUtil {

    public static boolean senMail(String host, String title, String mailTo, String content, String username, String password) throws Exception {
        Properties props = new Properties();
        props.put("mail.smtp.host", host);
        props.put("mail.smtp.auth", "true");
        Session s = Session.getInstance(props);
        s.setDebug(true);

        MimeMessage message = new MimeMessage(s);

        // 给消息对象设置发件人/收件人/主题/发信时间
        InternetAddress from = new InternetAddress(username);
        message.setFrom(from);
        InternetAddress to = new InternetAddress(mailTo);
        message.setRecipient(Message.RecipientType.TO, to);
        message.setSubject(title);
        message.setSentDate(new Date());

        // 给消息对象设置内容
        BodyPart mdp = new MimeBodyPart();// 新建一个存放信件内容的BodyPart对象
        mdp.setContent(content, "text/html;charset=utf-8");// 给BodyPart对象设置内容和格式/编码方式
        Multipart mm = new MimeMultipart();// 新建一个MimeMultipart对象用来存放BodyPart对
        // 象(事实上可以存放多个)
        mm.addBodyPart(mdp);// 将BodyPart加入到MimeMultipart对象中(可以加入多个BodyPart)
        message.setContent(mm);// 把mm作为消息对象的内容

        message.saveChanges();
        Transport transport = s.getTransport("smtp");
        transport.connect(host, username, password);
        transport.sendMessage(message, message.getAllRecipients());
        transport.close();
        return true;

    }

}
